<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-ellipsis :value="model.departName" :length="20" style="margin-left: 8px;"></j-ellipsis>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="客户级别" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <span style="margin-left: 8px;">{{ model.departLevel }}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="客户分组" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <span style="margin-left: 8px;">{{ model.groupId_dictText }}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="物流产品" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag placeholder="请选择物流产品" :getPopupContainer="null" v-model="productIdSearch" dict="hz_logistics_product,name,id,logistics"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row style="margin-bottom: 10px;">
          <a-button type="primary" @click="handleProduct">添加物流产品</a-button>
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <a-menu slot="overlay">
              <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
            </a-menu>
            <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
          </a-dropdown>
        </a-row>
        <a-table
          ref="table"
          size="middle"
          :scroll="{x:true}"
          bordered
          rowKey="code"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="false"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          class="j-table-force-nowrap"
        >
          <template slot="costRangeSlot" slot-scope="text, record">
            <div style="text-align: left;" v-if="getCostRangeSlot(text, 0)">公斤费：{{ getCostRangeSlot(text, 0) }}</div>
            <div style="text-align: left;" v-if="getCostRangeSlot(text, 1)">处理费：{{ getCostRangeSlot(text, 1) }}</div>
          </template>

          <template slot="ableStatusSlot" slot-scope="text, record">
            <span :style="{color: getColor(record)}">{{ record.ableStatusText }}</span>
          </template>

          <template slot="channelDescSlot" slot-scope="text, record">
            <j-ellipsis :value="text" :length="20"></j-ellipsis>
          </template>

          <template slot="effectBeginTimeSlot" slot-scope="text, record">
            <div v-if="record.effectBeginTime">开始时间：{{ record.effectBeginTime }}</div>
            <div v-if="record.effectEndTime">结束时间：{{ record.effectEndTime }}</div>
          </template>
          <span slot="action" slot-scope="text, record">
            <a @click="handleDel(record.code)">移除产品</a>
          </span>
        </a-table>
      </a-form-model>
      <sys-merchant-org-modal-child ref="modalForm" @ok="modalFormOk"></sys-merchant-org-modal-child>
    </j-form-container>
  </a-spin>
</template>

<script>
import { postAction, putAction, deleteAction } from '@/api/manage'
import SysMerchantOrgModalChild from '@/views/system/modules/SysMerchantOrgModalChild.vue'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
export default {
  name: "SysEditProductForm",
  mixins: [JeecgListMixin],
  components: {
    SysMerchantOrgModalChild
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data () {
    return {
      model:{
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {},
      url: {
        add: "/sys/sysDepart/add",
        edit: "/sys/sysDepart/edit",
        queryById: "/sys/sysDepart/queryById",
        list: "/logistics/productMerchant/logisticsProductMerchant/productList",
        delBatchProduct: "/logistics/productMerchant/logisticsProductMerchant/delBatchProduct"
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'物流产品名称',
          align:"center",
          dataIndex: 'name',
        },
        {
          title:'物流渠道',
          align:"center",
          dataIndex: 'channelName'
        },
        {
          title:'报价币种',
          align:"center",
          dataIndex: 'currencyType'
        },
        {
          title:'费用范围',
          align:"center",
          dataIndex: 'costRange',
          scopedSlots: { customRender: 'costRangeSlot' }
        },
        {
          title:'产品类型',
          align:"center",
          dataIndex: 'productType_dictText'
        },
        {
          title:'成本价方案',
          align:"center",
          dataIndex: 'costPriceId_dictText'
        },
        {
          title:'销售价方案',
          align:"center",
          dataIndex: 'salesPriceId'
        },
        {
          title:'状态',
          align:"center",
          dataIndex: 'ableStatus',
          scopedSlots: { customRender: 'ableStatusSlot' }
        },
        {
          title:'渠道描述',
          align:"center",
          dataIndex: 'channelDesc',
          scopedSlots: { customRender: 'channelDescSlot' }
        },
        {
          title:'时间',
          align:"center",
          dataIndex: 'effectBeginTime',
          scopedSlots: { customRender: 'effectBeginTimeSlot' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          width:147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      disableMixinCreated: true,
      productIdSearch: '',
      ipagination:{
        current: 1,
        pageSize: 9999
      },
      oriDataSource: []
    }
  },
  computed: {
    formDisabled(){
      return this.disabled
    },
  },
  created () {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  watch: {
    productIdSearch: {
      immediate: true,
      handler(val){
        // 只在初始化赋值
        if(this.dataSource.length > this.oriDataSource.length){
          this.oriDataSource = this.dataSource;
        }
        if(!val){
          this.dataSource = this.oriDataSource;
          return;
        }
        this.dataSource = this.oriDataSource.filter(item => item.id === val);
      }
    }
  },
  methods: {
    add () {
      this.edit(this.modelDefault);
    },
    edit (record) {
      this.model = Object.assign({}, record);
      this.visible = true;
      this.queryParam = {departId: this.model.id}
      this.loadData()
    },
    submitForm () {
      const that = this;
      // 触发表单验证
      that.$refs.form.validate(valid => {
        if (valid) {
          let httpurl = '';
          let Action;
          let params = Object.assign({}, that.model);
          params["orgCategory"] ="1";  //默认为公司创建
          if(!that.model.id){
            Action = postAction;
            httpurl+=that.url.add;
          }else{
            Action = putAction;
            httpurl+=that.url.edit;
          }
          that.confirmLoading = true;
          Action(httpurl,params).then((res)=>{
            if(res.success){
              that.$message.success(res.message);
              that.$emit('ok');
            }else{
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        }
      })
    },
    modalFormOk(){
      this.queryParam = {departId: this.model.id}
      this.loadData()
    },
    handleProduct(){
      let dataSource = this.dataSource.length > this.oriDataSource.length ? this.dataSource : this.oriDataSource;
      let codes = dataSource.map(item => item.code);
      codes = codes.join(',');
      this.$refs.modalForm.edit(this.model,codes);
      this.$refs.modalForm.title = "添加物流产品";
      this.$refs.modalForm.disableSubmit = false;
    },
    getColor(record){
      if(record.ableStatus === '1'){
        //草稿
        return '#ccc';
      }else if(record.ableStatus === '2'){
        //未生效
        return '#ccc';
      }else if(record.ableStatus === '3'){
        //生效中
        return '#1890FF';
      }else if(record.ableStatus === '4'){
        //已过期
        return 'orange';
      }else if(record.ableStatus === '5'){
        //禁用
        return 'red';
      }
    },
    getCostRangeSlot(text, type){
      return (text && text.split(',') && text.split(',')[type]) || '';
    },
    handleDel(ids){
      var that = this;
      that.$confirm({
        title: "确认删除",
        content: "是否删除选中数据?",
        onOk: function () {
          deleteAction(that.url.delBatchProduct, {departId: that.model.id, productCodes: ids}).then((res) => {
            if(res.success){
              that.$message.success(res.message);
              that.queryParam = {departId: that.model.id}
              that.loadData()
            }else{
              that.$message.warning(res.message);
            }
          })
        }
      });
    },
    batchDel(){
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        var ids = this.selectedRowKeys.join(',');
        this.handleDel(ids);
      }
    }
  }
}
</script>